package com.doudanhua.basecode.rabbitmq;

import com.doudanhua.basecode.jackson.JsonConvert;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author zhangqian
 * @Description TODO
 * @Date 2022/11/8 17:00
 */
@Configuration
public class RabbitMqConfig {
    public final static String EXCHANGE_BASECODE = "exchange_basecode";
    public final static String QUEUE_BASECODE = "queue_basecode";
    public final static String KEY_BASECODE = "basecode";

    public final static String EXCHANGE_DELAYED = "exchange_delayed";

    @Bean
    public DirectExchange baseCodeExchange() {
        return new DirectExchange(EXCHANGE_BASECODE, true, false);
    }

    @Bean
    public Queue baseCodeQueue() {
        return new Queue(QUEUE_BASECODE, true);
    }

    @Bean
    public Binding baseCodeBinding(DirectExchange baseCodeExchange, Queue baseCodeQueue) {
        return BindingBuilder.bind(baseCodeQueue).to(baseCodeExchange).with(KEY_BASECODE);
    }

    /**
     * 通过延迟插件实现
     * 1、声明一个类型为x-delayed-message的交换机
     * 2、参数添加一个x-delayed-type值为交换机的类型用于路由key的映射
     * 参考：https://blog.csdn.net/aa119101/article/details/124808880
     * @return
     */
    @Bean
    public CustomExchange delayExchange() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-delayed-type", "direct");
        return new CustomExchange(EXCHANGE_DELAYED, "x-delayed-message", true, false, args);
    }

    /**
     * 通过延迟插件实现
     * @param delayExchange
     * @param baseCodeQueue
     * @return
     */
    @Bean
    public Binding delayBinding(CustomExchange delayExchange, Queue baseCodeQueue) {
        return BindingBuilder.bind(baseCodeQueue).to(delayExchange).with(KEY_BASECODE).noargs();
    }
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setMessageConverter(new Jackson2JsonMessageConverter(JsonConvert.getObjectMapper()));
        return template;
    }

    @Bean
    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter(JsonConvert.getObjectMapper()));
        return factory;
    }
}
